import './public-path'
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'
import App from './App.vue'
import routes, { setupRouterGuard } from './router'
import store from './store'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'

let app: any = null
let router: any = null
let history: any = null

function render(props: any = {}) {
  const { container, getGlobalState } = props

  // 获取主应用传递的数据
  if(qiankunWindow.__POWERED_BY_QIANKUN__){
    if (props) {
      // 将主应用数据同步到子应用的状态管理中
      const state = getGlobalState?.() || {}
      store.commit('setToken', state.token)
      store.commit('setUserInfo', state.userInfo)
      console.log('父应用数据',state)
      store.commit('setIsLogin', !!state.token)
    }
  }

  history = createWebHistory(qiankunWindow.__POWERED_BY_QIANKUN__ ? '/app1' : '/')
  router = createRouter({
    history,
    routes
  })

  // 设置路由守卫
  setupRouterGuard(router)

  app = createApp(App)
  app.use(router)
  app.use(store)
  app.use(Antd)
  
  
  
  app.mount(container ? container.querySelector('#app') : '#app')
}

renderWithQiankun({
  mount(props) {
    console.log('app1 mount')
    render(props)
  },
  bootstrap() {
    console.log('app1 bootstrap')
  },
  unmount() {
    console.log('app1 unmount')
    app?.unmount()
    history?.destroy()
  },
  update(props) {
    console.log('app1 update')
    // 可以在这里处理主应用传递的props更新
    const { getGlobalState } = props
    const state = getGlobalState?.() || {}
    store.commit('setToken', state.token)
    store.commit('setUserInfo', state.userInfo)
    store.commit('setIsLogin', state.isLogin)
  }
})

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render()
}